package cn.main.service.impl;

import cn.main.core.AuthorityHelper;
import cn.main.core.UserSession;
import cn.main.dao.impl.DomainDaoImpl;
import cn.main.entity.sys.Role;
import cn.main.entity.sys.SysColumn;
import cn.main.entity.sys.SysFunction;
import cn.main.entity.sys.User;
import cn.main.service.ColumnService;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.org.mozilla.javascript.internal.Function;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Author: chengwei
 * Date:   2016/5/27
 * Time:   17:23
 */
@Service
public class ColumnServiceImpl implements ColumnService {
    
    @Resource
    private DomainDaoImpl dao;
    @Override
    public Map<String, Object> getColumn(User user) {
        Map<String,Object> map = new HashMap<>();
        dao.setCacheQueries(true);
        //获取栏目
//        List<Map<String,Object>> list = dao.queryForList("select * from sys_column order by show_order");
        List<SysColumn> columns = dao.getDomains(SysColumn.class);
        map.put("column",columns);
        
        for (SysColumn column : columns) {
            column.setFunctions(null);
        }
        
        return map;
    }

    @Override
    public Map<String, Object> getColumn(User user, String id) {
        return dao.queryForMap("select * from sys_column where column_id = ?",id);
    }

    @Override
    @Transactional
    public void saveOrUpdate(UserSession session, SysColumn column) {
        
        dao.saveDomain(column);
    }

    @Override
    @Transactional
    public void deleteColumn(UserSession session,String columnId) {
        SysColumn column = new SysColumn();
        column.setColumnId(columnId);
        dao.deleteDomain(column);
    }
    
    public SysColumn findColumnById(UserSession session,String columnId) {
        SysColumn column = dao.getDomain(columnId,SysColumn.class);
        column.setFunctions(null);
        return column;
    }

    @Override
    public List<SysColumn> getColumnList(UserSession session) {
        List<SysColumn> columns = dao.getDomains(SysColumn.class,"order by show_order");
        for (int i = columns.size()-1;i >= 0;i--) {
            if (!AuthorityHelper.hasColumnAuthority(session,columns.get(i))) {
                columns.remove(i);
                continue;
            }
            columns.get(i).setFunctions(null);
        }
        return columns;
    }

    @Override
    public List<SysColumn> getColumnList() {
        List<SysColumn> columns = dao.getDomains(SysColumn.class,"order by show_order");
        for (int i = columns.size()-1;i >= 0;i--) {
            columns.get(i).setFunctions(null);
        }
        return columns;
    }
}
